package com.toocms.ipaynow

import android.content.Context
import com.ipaynow.plugin.api.IpaynowPlugin
import com.ipaynow.plugin.manager.route.dto.ResponseParams
import com.ipaynow.plugin.manager.route.impl.ReceivePayResult

class Ipaynow {
    var callback: ((code: String, msg: String) -> Unit)? = null
    val receivePayResult = object : ReceivePayResult {
        override fun onIpaynowTransResult(responseParams: ResponseParams?) {
            val respCode = responseParams!!.respCode
            val errorCode = responseParams!!.errorCode
            val errorMsg = responseParams!!.respMsg
            val temp = StringBuilder()
            if (respCode == "00") {
                temp.append("交易状态:成功")
            } else if (respCode == "02") {
                temp.append("交易状态:取消")
            } else if (respCode == "01") {
                temp.append("交易状态:失败").append("\n").append("错误码:").append(errorCode)
                    .append("原因:$errorMsg")
            } else if (respCode == "03") {
                temp.append("交易状态:未知").append("\n").append("原因:$errorMsg")
            } else {
                temp.append("respCode=").append(respCode).append("\n").append("respMsg=")
                    .append(errorMsg)
            }
            callback?.invoke(respCode, temp.toString())
        }

        override fun onPluginError(p0: Throwable?) {

        }

    }

    fun wechatPayment(
        context: Context,
        message: String,
        callback: ((code: String, msg: String) -> Unit)? = null
    ) {
        this@Ipaynow.callback = callback
        IpaynowPlugin.getInstance().init(context)
            .apply {
                setCustomLoading(defaultLoading)
                    .setCallResultReceiver(receivePayResult)
                    .pay(message)
            }
    }

}